//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

namespace OpenLS.Spreadsheet.UI
{
    /// <summary>
    /// Interaction logic for DocumentsControl.xaml
    /// </summary>
    public partial class DocumentsResources 
    {
        public DocumentsResources()
        {
            InitializeComponent();
        }
        void OnClick (object sender, RoutedEventArgs args)
        {
            var menuItem = (MenuItem) sender;
            var doc = (SpreadsheetDocument) menuItem.DataContext;
            object documents = SpreadsheetElement.GetDocuments(menuItem);
            var view =  CollectionViewSource.GetDefaultView(documents);
            view.MoveCurrentTo(doc);
            args.Handled = true;
        }

        void OnUnhideWorkbook(object sender, ExecutedRoutedEventArgs e)
        {
            e.Handled = true;
            var documents = SpreadsheetElement.GetDocuments((DependencyObject)sender);
            IEnumerable<DocumentContainer> docs = Enumerable.Where(documents, dd => !dd.IsVisible);
            var view = CollectionViewSource.GetDefaultView(documents);
            foreach (DocumentContainer doc in docs)
            {
                doc.IsVisible = true;
                view.MoveCurrentTo(doc);
            }
        }

        private void OnHideWorkbook(object sender, ExecutedRoutedEventArgs e)
        {
            e.Handled = true;
            object documents = SpreadsheetElement.GetDocuments((DependencyObject) sender);
            var view = CollectionViewSource.GetDefaultView(documents);
            var c = (DocumentContainer) view.CurrentItem;
            c.IsVisible = false;
            if (!view.IsEmpty)
            {
                if (view.CurrentPosition == 0)
                    view.MoveCurrentToNext();
                else
                    view.MoveCurrentToPrevious();
            }
        }

        private void OnCanUnhideWorkbook(object sender, CanExecuteRoutedEventArgs e)
        {
            var documents = SpreadsheetElement.GetDocuments((DependencyObject)sender);
            e.CanExecute = Enumerable.Any(documents, dd => !dd.IsVisible);
            e.Handled = true;

        }
    }
}
